package com.example.demo.config;

import com.example.demo.interceptor.AuthorizationInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web配置类
 * 配置拦截器和跨域等
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    private final AuthorizationInterceptor authorizationInterceptor;
    
    public WebConfig(AuthorizationInterceptor authorizationInterceptor) {
        this.authorizationInterceptor = authorizationInterceptor;
    }
    
    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authorizationInterceptor)
                .addPathPatterns("/api/admin/**", "/api/user/articles/**", "/api/test/permission-test") // 拦截管理员接口、用户文章接口和权限测试接口
                .excludePathPatterns(
                    "/api/user/login",        // 排除登录接口
                    "/api/user/register",     // 排除注册接口
                    "/api/user/check-*",      // 排除验证接口
                    "/api/blog/**",           // 排除博客公开接口
                    "/api/test/system-status",  // 排除系统状态接口
                    "/api/test/user-permissions/**", // 排除用户权限查询接口
                    "/api/test/jwt-diagnosis",    // 排除JWT诊断接口
                    "/api/test/no-permission-test", // 排除无权限测试接口
                    "/favicon.ico",           // 排除图标
                    "/error"                  // 排除错误页面
                );
    }
    
    /**
     * 配置跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOriginPatterns("http://localhost:*", "http://127.0.0.1:*", "file://*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .exposedHeaders("Authorization")
                .maxAge(3600);
    }
}
